from qcloudsms_py import SmsSingleSender

from . import settings

from luffyapi.utils.logger import get_logger
import random

logger = get_logger()


# 随机生成四位数字验证码

# 字符串+数字 在python中报错---》python是动态强类型（不同类型之间不能之间运算）
def get_code():
    code = ''
    for i in range(6):
        code += str(random.randint(0, 9))  # 更牛逼的方法自己实现

    return code


def send(phone, code):
    ssender = SmsSingleSender(settings.APPID, settings.APPKEY)
    try:
        result = ssender.send_with_param(86, phone, settings.TEMPLATE_ID, [code, ], sign=settings.SMS_SING, extend="",
                                         ext="")
        if result.get('result') == 0:
            return True
        else:
            # 记录日志
            logger.warning('%s手机号，短信发送失败' % phone)
            return False
    except Exception as e:
        # 记录日志
        logger.warning('%s手机号，短信发送时出异常' % phone)
        return False


